package day32;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

// Java8四大内置核心函数式接口
// java.util.function包下还定义了其它一些常用函数式接口
public class Demo02 {
	public static void main(String[] args) {
		test04();
	}

	// 断言型接口: Predicate<T>
	// 方法: boolean test(T t);
	private static void test04() {
		List<String> target = Arrays.asList("asfd", "febvre", "sdf", "fewgvfdvre", "1231r23f",
				"vr3g54g");
		//		Predicate<String>pre = new Predicate<String>() {
		//			@Override
		//			public boolean test(String t) {
		//				return t.length() == 3 || t.length() == 4;
		//			}
		//		};
		Predicate<String> pre = t -> t.length() == 3 || t.length() == 4;
		List<String> list = strFilter(target, pre);
		System.out.println(list);
	}

	// 需求: 将满足条件的字符串添加到集合中
	public static List<String> strFilter(Collection<String> target, Predicate<String> pre) {
		List<String> list = new ArrayList<String>();
		for (String s : target) {
			if (pre.test(s)) {
				list.add(s);
			}
		}
		return list;
	}

	// 函数型接口: Function<T, R>
	// 方法: R apply(T t);
	private static void test03() {
		String str = "fdgdgbfrb";
		//		Function<String, String> fun = new Function<String, String>() {
		//			@Override
		//			public String apply(String t) {
		//				return t.toUpperCase();
		//			}
		//		};
		Function<String, String> fun = t -> t.toUpperCase();
		String newStr = strHandler(str, fun);
		System.out.println(newStr);
	}

	// 需求: 处理字符串
	public static String strHandler(String str, Function<String, String> fun) {
		return fun.apply(str);
	}

	// 供给型接口: Supplier<T>
	// 方法: T get();
	private static void test02() {
		//		Supplier<Integer> sup = new Supplier<Integer>() {
		//			@Override
		//			public Integer get() {
		//				return new Random().nextInt(100);
		//			}
		//		};
		Supplier<Integer> sup = () -> new Random().nextInt(100);
		List<Integer> list = getNumList(10, sup);
		System.out.println(list);
	}

	// 需求: 生产指定数量的整数, 将这些整数存入一个List
	public static List<Integer> getNumList(int count, Supplier<Integer> sup) {
		List<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < count; i++) {
			list.add(sup.get());
		}
		return list;
	}

	// 消费型接口: Consumer<T>
	// 方法: void accept(T t);
	private static void test01() {
		Consumer<Double> con = m -> System.out.println("买一把大宝剑");
		happy(2000, con);
	}

	public static void happy(double money, Consumer<Double> con) {
		System.out.print("花" + money + "出去happy, 打算");
		con.accept(money);
	}
}
